package finn.movingheadtracker;

import java.util.ArrayList;
import java.util.List;

public class DmxMerger {
	public static List<MergedUniverse> mergedUniverses = new ArrayList<MergedUniverse>();
	
	static List<Universe> universes = new ArrayList<Universe>();
	
	public DmxMerger() {
	}
	
	public static Universe getUniverse(int universe_id){
		if(universes.size()==0){
			Logger.log(Logger.ERROR, "No Universes Available");
			return null;
		}
		for(Universe un: universes){
			if(un.id==universe_id){
				return un;
			}
		}
		Logger.log(Logger.ERROR, "Universe not found");
		return null;
	}
	
	public static void setUniverseDmx(int universe_id, DmxValue[] values){
		for(MergedUniverse mu: mergedUniverses){
			mu.setUniverseDmx(universe_id, values);
		}
	}
	
	public static void setOutput(int universe_id, DmxValue[] values){
		DmxMerger.getUniverse(universe_id).change(values);
	}
	
	public static void setArtnetInput(int ArtnetUniverseId, int SubnetUniverseId, byte[] values){
		for(Universe an : universes){
			if(an.getClass() == UniverseArtnet.class && ((UniverseArtnet)an).direction == Universe.IN){
				if(((UniverseArtnet)an).ArtnetUniverseId == ArtnetUniverseId && ((UniverseArtnet)an).SubnetUniverseId == SubnetUniverseId){
					an.change(values);
					return;
				}
			}
		}
	}
	

	/**
	 * Get Value of Universe
	 * @param universe_id Specify Universe
	 * @return byte value of this channel
	 */
	public static byte getValue(int universe_id, int channel){
		Universe un = DmxMerger.getUniverse(universe_id);
		if(un==null){
			return 0;
		}
		return un.getChannelValue(channel);
	}
	
	public static List<Universe> getOutputUniverses(short type){
		List<Universe> lst = new ArrayList<Universe>(); 
		for(Universe un: universes){
			if(type == Universe.ARTNET && un.getClass()==UniverseArtnet.class){
				lst.add(un);
			}
		}
		return lst;
	}
	
	public static MergedUniverse getMergedUniverse(int id){
		for(MergedUniverse mu:mergedUniverses){
			if(mu.id==id){
				return mu;
			}
		}
		return new MergedUniverse(0);
	}
	
	public static void createMergedUnverse(){
		int available=1;
		if(mergedUniverses.size()==0){
			mergedUniverses.add(new MergedUniverse(1));
			return;
		}
		for(MergedUniverse mu:mergedUniverses){
			if(available<=mu.id){
				available = mu.id + 1;
			}
		}
		mergedUniverses.add(new MergedUniverse(available));
	}
}
